<template>
    <rx-layout>
        <div slot="left" width="210" showButton="true" :showModuleLeft="false" :headerTitle="i18n('list.formClass','表单分类')">
            <rx-fit style="padding: 4px;">
                <rx-category-treeeditor
                    cat-key="FORM"
                    :statisticConfig="statisticConfig"
                    :edit="true"
                    @handSelect="handSelect"
                    :async="true"
                    v-if="isShowManageTree"
                    :isAdmin="isManageToTree"
                    :checkToDel="true"
                ></rx-category-treeeditor>
            </rx-fit>
        </div>
        <div slot="center" style>
            <rx-fit :isheader="isheader">
                <div slot="toolheader" border="false" foldbtn="false">
                    <div class="table-operator">
                        <a-dropdown style="margin-left: 0px" v-if="findAuthRight('add')">
                            <a-menu slot="overlay" @click="selectItem">
                                <a-menu-item key="dragform"><my-icon type="icontuozhuai"/>{{i18n('list.dragCreate','拖拽建单')}}</a-menu-item>
                                <a-menu-item key="dragboform"><my-icon type="iconmoxingjiandan"/>{{i18n('list.newByFormDef','基于模型建单')}}</a-menu-item>
                                <a-menu-item key="custom"><my-icon type="iconzidingyibiaodan"/>{{i18n('list.customerForm','自定义表单')}}</a-menu-item>
                                <a-menu-item key="outsideUrl"><my-icon type="iconVue3_correlation"/>{{i18n('list.ExtUrlForm','外部URL表单')}}</a-menu-item>
                            </a-menu>
                            <a-button style="margin-left: 8px" type="primary">
                                {{i18n('list.addForm','新建单据')}}
                                <a-icon type="down"/>

                            </a-button>
                        </a-dropdown>
                        <a-button type="primary" v-if="!isAppDevelop && selectedRowKeys.length > 0 " icon="redo"
                                  @click="changeApp('FORM',selectedRows,'id','name','appId','categoryId',changeAppId)">
                            {{i18n('list.ChangeApplication','变更应用')}}
                        </a-button>
                        <a-button type="danger"
                                  v-if="findAuthRight('delete') && removeEnable && selectedRowKeys.length > 0 "
                                  icon="delete" @click="delByIds(selectedRowKeys)">
                            {{$ti18('rxList.delBtn','删除')}}
                        </a-button>
                        <a-button type="primary"
                                  v-if="selectedRowKeys.length > 0"
                                  icon="switcher" @click="changeExport(exportConf)">
                            {{$ti18('rxList.changeExport','切换导出')}}
                        </a-button>
                        <a-button v-if="selectedRowKeys.length > 0"
                                  type="primary"
                                  icon="switcher" @click="openCategoryDialog">
                            {{$ti18('rxList.changeCategory','切换分类')}}
                        </a-button>
                    </div>
                    <span class="search-btn-box" v-if="!isheader">
            <span class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>
                {{$ti18('rxList.leachBtn','过滤')}}
            </span>
          </span>
                </div>
                <div btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel"
                     @close="closeSearchbar">
                    <a-form :layout="colLayout">
                        <a-row :gutter="24">
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.name','名称')">
                                    <a-input :placeholder="i18n('form.name','名称','input')" v-model="queryParam.Q_NAME__S_LK" allowClear/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.alias','别名')">
                                    <a-input :placeholder="i18n('form.alias','别名','input')" v-model="queryParam.Q_ALIAS__S_LK" allowClear/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan" v-if="isheader">
                              <span class="table-page-search-submitButtons">
                                <a-button type="primary" icon="search" @click="search">{{$ti18('rxList.searchBtn','查询')}}</a-button>
                                <a-button style="margin-left: 4px" @click="cancel">{{$ti18('rxList.resetBtn','重置')}}</a-button>
                                <a @click="toggleAdvanced" style="margin-left: 8px">
                                  {{ advanced ? $ti18('rxList.putAwayBtn','收起') : $ti18('rxList.openBtn','收起') }}
                                  <a-icon :type="advanced ? 'up' : 'down'"/>
                                </a>
                              </span>
                            </a-col>
                            <template v-if="advanced">
                                <a-col :span="colSpan">
                                    <a-form-item :label="i18n('form.status','发布状态')">
                                        <a-select v-model="queryParam.Q_DEPLOYED__I_EQ" allowClear>
                                            <a-select-option value="">{{$ti18('rxDecorator.select','请选择')}}</a-select-option>
                                            <a-select-option :value="1">{{i18n("form.publish","发布")}}</a-select-option>
                                            <a-select-option :value="0">{{i18n("form.NotPublish","未发布")}}</a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                            </template>
                            <a-col :span="colSpan" v-if="!curApp.appId">
                                <a-form-item :label="$ti18('rxForm.appId', '应用')">
                                    <rx-search-app @change="appChange" v-model="searchApps">
                                    </rx-search-app>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>

                </div>
                <rx-grid
                    ref="table"
                    :showColumnsMenu="true"
                    bordered
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :columns="columns"
                    :defaultPageSize="15"
                    :allowMoveColumn="true"
                    url="/api-form/form/core/formPc/query"
                    :queryParam="queryParam"
                    data-field="result.data"
                    :pageSizeOptions="[10, 15,30, 40]"
                    id-field="id"
                    :loadDataOnstart="true"
                    @selectChange="onSelectChange"
                >
                     <span slot="exportApp">
                         {{ exportI18n('export.isExport','导出') }}
                        <export-app/>
                    </span>
                    <span slot="type" slot-scope="{ text, record }">
                        <a-tag :color="typeMap[text].color">
                            <span>{{ typeMap[text].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="deployed" slot-scope="{ text, record }">
                        <a-tag :color="statusMap[text].color">
                            <span>{{ statusMap[text].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="appId" slot-scope="{ text, record }">
                        {{allApps[text]?$i18(allApps[text].appName,'应用名称'):$ti18('rxList.noAppName','无')}}
                    </span>
                    <span slot="isExport" slot-scope="{ text, record }">
                        <a-tag :color="text == 1 ? 'green' : 'red'">
                            <span>{{ text == 1 ? exportI18n('export.yes','是') : exportI18n('export.no','否') }}</span>
                        </a-tag>
                    </span>
                    <span slot="action" slot-scope="{ text, record }" class="actionIcons">
                        <span @click="design(record)" v-if="findAuthRight('edit') && containType(record.type)">{{i18n('list.design','设计')}}</span>
                        <span @click="editFormPc(record)" v-if="findAuthRight('edit') && record.type == 'SEL-DEV'" style="padding-left: 0;">{{$ti18('rxList.editBtn','编辑')}}</span><span @click="editOutSideUrlFormPc(record)" v-if="findAuthRight('edit') && record.type == 'OUTSIDE-URL'" style="padding-left: 0;">编辑</span>
                        <span v-if="(containType(record.type) && record.deployed == 0 )" @click="deploy(record.id, true)">{{i18n('form.publish','发布')}}</span>
                        <span v-if="(containType(record.type) && record.deployed == 1 )" @click="deploy(record.id, false)">{{i18n('list.prohibit','禁止')}}</span>
                        <span @click="copyForm(record)" v-if="containType(record.type)">{{i18n('list.copy','复制')}}</span>
                        <span @click="delByIds([record.id])" v-if="findAuthRight('delete')">{{$ti18('rxList.delBtn','删除')}}</span>
                        <span @click="setExport(record,exportConf)">{{record.isExport == 1 ? exportI18n('export.noExport','不导出') : exportI18n('export.exported','导出')}}</span>
                        <span v-if="!curApp.appId" @click="share(record)">{{$ti18('rxList.share','共享')}}</span>
                    </span>
                </rx-grid>
            </rx-fit>
        </div>
    </rx-layout>
</template>

<script>
import FormPcApi from '@/api/form/core/formPc'
import FormPcEdit from './FormPcEdit'
import {BaseList, RxLayout, RxGrid, RxFit, Util, GSpan, Dialog} from "@lowcode/jpaas-common-lib"
import RxCategoryTreeeditor from '@/components/redxun/rx-category-treeeditor'
import FormPermissionApi from '@/api/form/core/formPermission'
import FormPcVersions from './FormPcVersions'
import CopyFormPc from './CopyFormPc'

import FormPcCustomEdit from './FormPcCustomEdit'
import changeAppJs from "@/views/modules/share/changeApp"
import FormPcOutsideUrlEdit from "./FormPcOutsideUrlEdit";
import SysTreeApi from "@/api/system/core/sysTree";
import { mapState} from 'vuex'
import exportApp from "@/views/modules/share/exportApp";
import FormResourceShareApi from "@/api/form/core/formResourceShare";
import AppSearch from "@/views/modules/share/AppSearch";
import RxSearchApp from "@/views/modules/share/rx-search-app";
import switchExport from "@/utils/switchExport";
import ChangeCategory from "@/views/modules/share/ChangeCategory.js"

export default {
    name: 'FormPcList',
    mixins: [BaseList, changeAppJs,AppSearch,switchExport,ChangeCategory],
    components: {
        RxLayout,
        RxGrid,
        RxFit,
        RxCategoryTreeeditor,
        GSpan,
        exportApp,
        RxSearchApp
    },
    computed: {
        ...mapState({
            //所属应用
            allApps: state => state.appSetting ? state.appSetting.allApps : {}
        }),
    },
    data() {
        return {
            columns: [
                {
                    title: this.$ti18('rxList.index','序号'),
                    scopedSlots: {customRender: 'serial'},
                    dataIndex: 'serial',
                    type: 'indexColumn',
                    width: 60
                },
                {title: this.i18n('form.name','名称'), dataIndex: 'name',width: 180,  sorter: true, sortField: 'NAME_'},
                {title: this.i18n('form.alias','别名'), dataIndex: 'alias', width: 160, sorter: true, sortField: 'ALIAS_'},
                {
                    title: this.i18n('form.type','类型'),
                    dataIndex: 'type',
                    sorter: true,
                    sortField: 'TYPE_',
                    width: 200,
                    scopedSlots: {customRender: 'type'}
                },
                {
                    title: this.i18n('form.deployed','发布状态'),
                    dataIndex: 'deployed',
                    width: 140,
                    sorter: true,
                    sortField: 'DEPLOYED_',
                    scopedSlots: {customRender: 'deployed'}
                },
                {title: this.i18n('form.application','所属应用'), dataIndex: 'appId', width: 100, sortField: 'APP_ID_',scopedSlots: {customRender: 'appId'}},
                {
                    dataIndex: 'isExport',
                    slots: { title: 'exportApp' },
                    width: 120,
                    scopedSlots: {customRender: 'isExport'}
                },                {title: this.$ti18('rxForm.createTime','创建时间'), dataIndex: 'createTime', sorter: true, sortField: 'CREATE_TIME_', width: 160},
                {title: this.i18n('form.action','操作'), dataIndex: 'action', fixed: 'right', scopedSlots: {customRender: 'action'}, width: 180},
            ],
            component: FormPcEdit,
            comment: this.i18n("list.comment","表单"),
            widthHeight: ['800px', '600px'],
            statusMap: {

                1: {color: 'green', text: this.i18n("form.publish","发布")},
                0: {color: 'red', text: this.i18n("form.NotPublish","未发布")},
            },
            //this.i18n('typeMap.',
            typeMap: {
                'ONLINE-DESIGN': {color: 'green', text: this.i18n('list.onlineCreate','编辑建单')},
                'EASY-DESIGN': {color: 'blue', text: this.i18n('list.dragCreate','拖拽建单')},
                'DRAG-DESIGN': {color: 'blue', text: this.i18n('list.dragCreate','拖拽建单')},
                'GENBYBO': {color: 'red', text: this.i18n('list.boFormCreate','模型编辑建单')},
                'EASY-GENBYBO': {color: 'red', text: this.i18n('list.dragBoFormCreate','模型拖拽建单')},
                'DRAG-GENBYBO': {color: 'red', text: this.i18n('list.dragBoFormCreate','模型拖拽建单')},
                'SEL-DEV': {color: 'orange', text: this.i18n('typeMap.SELDEV','自定义表单')},
                'OUTSIDE-URL': {color: 'orange', text: this.i18n('typeMap.OUTSIDE','外部URL表单')},
            },
            curTree: {},
            statisticConfig: {
                type: "static_form",
                table: "FORM_PC t",
                field: "CATEGORY_ID_",
                whereConf: []
            },
            /**
             * 导出配置
             */
            exportConf:{
                Api:FormPcApi,
                id:"id"
            },
            //变更分类配置
            categoryConfig:{
                Api:FormPcApi,
                catKey:"FORM",
                gridRef:"table"
            },
            treeId:'',//选中左边树的ID
        }
    },
    created() {
        this.isUserManager(this.$route.query.appId);
        this.needFilterAppId("isAppMenu");
        this.columns=this.removeAppColumn(this.curApp.appId,this.columns)
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"formPc",key);
        },
        exportI18n(name,text,key){
            return this.$ti18(name,text,"appExport",key);
        },
        //资源共享
        share(record){
            let self=this;
            FormResourceShareApi.getShareApps(record.id).then(res => {
                let initData=res.data;
                if(!initData){
                    initData=[];
                }
                self.showAppDialog(initData,record.id,record.alias,record.name);
            });
        },
        showAppDialog(initData,resId,resKey,resName){
            Dialog.openSystemAppDialog({
                curVm: this, widthHeight: ['1150px', '735px'],
                data:{initSelected: initData,isDevelopApp:true,isSelectApp:true}
            }, function (self, data) {
                //保存共享信息
                FormResourceShareApi.saveShareApps(data.apps,resId,resKey,resName,"7").then(res => {
                    if (res.success && res.code == 200) {
                    }
                });
            })
        },
        containType(type) {
            if (type != "SEL-DEV" && type != "OUTSIDE-URL") {
                return true;
            }
            return false;
        },
        permissionSeting(id) {
            FormPermissionApi.permissionSeting(this, id, 'form')
        },
        selectItem(e) {
            var key = e.key
            this.newForm(key)
        },
        delById(ids) {
            return FormPcApi.del({ids: ids.join(',')})
        },
        design(record) {
            let url = ''
            if (record.type == 'DRAG-DESIGN')  {
                url += '/dragform/design/'
            }else {
                url += '/dragform/bo/'
            }
            if(!url){
                return;
            }
            url += record.pkId;
            url = this.appendUrl(url);
            window.open(url)
        },
        editFormPc(record) {
            var config = {
                curVm: this,
                component: FormPcCustomEdit,
                title: this.$ti18("rxList.editBtn",'编辑')+" "+this.i18n("typeMap.SELDEV",'自定义表单'),
                data: {
                    id: record.id,
                },
                widthHeight: ['900px', '600px']
            }
            Util.open(config, function (action, data) {
            })
        },
        editOutSideUrlFormPc(record) {
            var config = {
                curVm: this,
                component: FormPcOutsideUrlEdit,
                title: this.$ti18("rxList.editBtn",'编辑')+" "+this.i18n("typeMap.OUTSIDE",'外部URL表单'),
                data: {
                    id: record.id,
                },
                widthHeight: ['900px', '600px']
            }
            Util.open(config, function (action, data) {
            })
        },
        appendUrl(url) {
            if (this.curApp.appId) {
                url += "?appId=" + this.curApp.appId;
                if(this.treeId && this.treeId!='0'){
                    url +="&treeId=" + this.treeId
                }
            }else if(this.treeId && this.treeId!='0'){
                url +="?treeId=" + this.treeId
            }
            return url;
        },
        newForm(key) {
            let appId = this.curApp.appId;
            let self_ = this;
            SysTreeApi.getByCatKey('FORM', appId).then((res) => {
                if (res.length > 0) {
                    let url = ''
                    if (key == 'dragform')  {
                        url += '/dragform/design/-1';
                        url = self_.appendUrl(url);
                        window.open(url)
                    }else if (key == 'dragboform'){
                        url += '/dragform/bo/-1';
                        url = self_.appendUrl(url);
                        window.open(url)
                    }
                    else if (key == 'outsideUrl') {
                        var config = {
                            curVm: self_,
                            component: FormPcOutsideUrlEdit,
                            title: this.$ti18("rxList.newBtn",'添加')+" "+this.i18n("typeMap.OUTSIDE",'外部URL表单'),
                            widthHeight: ['900px', '600px'],
                        }
                        Util.open(config, function (action, data) {
                        })
                    }
                    else if (key == 'custom') {
                        var config = {
                            curVm: self_,
                            component: FormPcCustomEdit,
                            title: this.$ti18("rxList.newBtn",'添加')+" "+this.i18n("typeMap.SELDEV",'自定义表单'),
                            widthHeight: ['900px', '600px'],
                        }
                        Util.open(config, function (action, data) {
                        })
                    }

                } else {
                    //没有分类节点，报错
                    this.$message.error(this.i18n('msg.NoType','请先新建分类'));
                }
            })

        },
        handSelect(curRow) {
            this.curTree = curRow;
            this.treeId = curRow.treeId;
            let params={
                Q_CATEGORY_ID__S_EQ:""
            }
            if(this.treeId!="0"){
                params.Q_CATEGORY_ID__S_EQ=this.treeId;
            }else {
                params.Q_CATEGORY_ID__S_EQ="";
            }
            this.loadData(params);
        },
        deploy(formId, status) {
            var msg = status ? this.i18n('msg.deploy','您确定需要发布选择的表单吗？') : this.i18n('msg.disDeploy','您确定需要禁止发布选择的表单吗？')
            var self_ = this
            this.$confirm({
                title: self_.$ti18('rxMsa.actionTips','操作提示'),
                content: msg,
                okText: self_.$ti18("rxForm.okBtn","确定"),
                cancelText: self_.$ti18("rxForm.cancelBtn","取消"),
                onOk() {
                    FormPcApi.deploy(formId, false).then((res) => {
                        var message = status ? self_.i18n('msg.deployed','发布成功') : self_.i18n('msg.prohibited','禁止成功')
                        if (!res.success) {
                            message = res.message
                        }
                        self_.$notification[res.success ? 'success' : 'error']({
                            message: self_.$ti18('rxMsa.actionTips','操作提示'),
                            description: message,
                        })
                        self_.refreshGrid()
                    })
                },
            })
        },

        //版本管理
        versionMgr(record) {
            var config = {
                curVm: this,
                data: {alias: record.alias},
                component: FormPcVersions,
                title: this.i18n("list.version",'表单版本管理')+'--' + record.name,
                widthHeight: ['1000px', '600px'],
            }

            Util.open(config, function (action) {
            })
        },

        //复制表单
        copyForm(record) {
            var self_ = this;
            var config = {
                curVm: this,
                data: {record: record},
                component: CopyFormPc,
                title: this.i18n("list.copyForm",'表单复制')+'--' + record.name,
                widthHeight: ['750px', '450px'],
            }
            Util.open(config, function (action, data) {
                if (action != 'ok') {
                    return
                }
                FormPcApi.copyNew(data).then((res) => {
                    self_.refreshGrid()
                })
            })
        },


        search() {
            this.$refs.table.loadData();
        },


        cancel() {
            this.resetSearch();
        },
        closeSearchbar() {
            //关闭过滤弹窗；（点击X触发）
            this.fitSearch = false;
        },
        changeAppId(selectedRows) {
            FormPcApi.saveList(selectedRows);
        },

    }
}
</script>
<style scoped>

</style>

